﻿//定义js命名空间
Ext.namespace("Infrastructure.Menu");

Infrastructure.Menu.GridPanel = Ext.extend(Ext.ux.maximgb.tg.GridPanel, {
	userId: '',
	initFlag: false,
	//constructor
	constructor: function (cfg) {
		//prepare
		cfg = cfg || {};
		var grid = this;
		var updateUserMenu = this.onUpdateUserMenu;

		this.tbar = [{
			xtype: "tbbutton",
			minWidth: 80,
			ref: '../saveBtn',
			text: "保存",
			disabled: true,
			cls: "x-btn-text-icon",
			icon: "/Content/icons/report_disk.png",
			handler: updateUserMenu,
			scope: grid
		}];

		var MenuRecord = Ext.data.Record.create([
			{ name: 'Name' },
			{ name: 'TreeCode' },
			{ name: 'Id', type: 'string' },
			{ name: 'ParentId', type: 'auto' },
			{ name: 'Leaf', type: 'bool' },
			{ name: 'Level', type: 'int' },
			{ name: 'ActionName', type: 'string' },
			{ name: 'ControllerName', type: 'string' },
			{ name: 'Index', type: 'int' },
			{ name: 'Description', type: 'string' },
			{ name: 'URL', type: 'string' },
			{ name: 'BigIcon', type: 'string' },
			{ name: 'SmallIcon', type: 'string' },
			{ name: 'IsExtPage', type: 'bool' },
			{ name: 'IsFunction', type: 'bool' },
			{ type: 'date', name: 'CreateTime' }
		]);

		var MenuStore = new Ext.ux.maximgb.tg.AdjacencyListStore({
			url: '/InfraRole/GetMenuGrid',
			reader: new Ext.data.JsonReader({
				id: 'Id',
				root: 'data'
			}, MenuRecord)
		});
		MenuStore.setDefaultSort('Index', 'ASC');

		MenuStore.isLoadedNode = function (rc) {
			return true;
		};

		var MenuSM = new Ext.grid.CheckboxSelectionModel({
			header: '',
			checkOnly: true,
			listeners: {
				'rowselect': function (sm, rowIndex, r) {
					selectGridNode(this.grid, sm, rowIndex, r);
				},
				'rowdeselect': function (sm, rowIndex, r) {
					deSelectGridNode(this.grid, sm, rowIndex, r);
				}
			}
		});

		var selectGridNode = function (grid, sm, rowIndex, r) {
			var gridStore = grid.getStore();
			//选当前节点的上级节点
			var pRecord = gridStore.getNodeParent(r);
			if (pRecord != null) {
				var pIndex = gridStore.indexOf(pRecord);
				if (pIndex != -1) {
					sm.selections.add(MenuStore.getAt(pIndex));
					grid.getView().onRowSelect(pIndex);
					// 递归选择上级节点
					selectGridNode(grid, sm, pIndex, pRecord);
				}
			}
		}

		var deSelectGridNode = function (grid, sm, rowIndex, r) {
			var gridStore = grid.getStore();
			//反选字节点
			var records = gridStore.getNodeChildren(r);
			for (var i = 0; i < records.length; i++) {
				var index = gridStore.indexOf(records[i]);
				if (index != -1) {
					sm.selections.remove(MenuStore.getAt(index));
					grid.getView().onRowDeselect(index);
					// 递归反选字节点
					deSelectGridNode(grid, sm, index, records[i]);
				}
			}
		}

		//        var rootReocdData = {
		//            "Name": "所有菜单",
		//            "Code": "",
		//            "Id": "0",
		//            "ParentId": null,
		//            "Leaf": null,
		//            "Level": 0,
		//            "IsExtPage": null

		//        };
		//        

		//        var rootReocd = new MenuStore.recordType(rootReocdData, 0);
		//        MenuStore.insert(0, rootReocd);

		//读取菜单
		//MenuStore.load({
		//    add: true
		//});
		MenuSM.lock();

		Infrastructure.Menu.GridPanel.superclass.constructor.call(this, Ext.apply({
			region: "center",
			enableColumnMove: false,
			frame: true,
			border: true,
			layout: "fit",
			loadMask: true,
			sm: MenuSM,
			store: MenuStore,
			master_column_id: 'Name',
			columns: [MenuSM, {
				id: 'Name',
				header: "菜单名",
				width: 160,
				dataIndex: 'Name'
			}, {
				header: "代码",
				width: 70,
				dataIndex: 'TreeCode'
			}, {
				header: "Controller名称",
				dataIndex: 'ControllerName'
			}, {
				header: "Action名称",
				dataIndex: 'ActionName'
			}, {
				header: "排序",
				dataIndex: 'Index',
				width: 60
			}, {
				header: "描述",
				dataIndex: 'Description'
			}, {
				header: "大图标",
				dataIndex: 'BigIcon'
			}, {
				header: "小图标",
				dataIndex: 'SmallIcon'
			}, {
				header: "URL",
				dataIndex: 'URL'
			}, {
				header: "是否叶子菜单",
				dataIndex: 'Leaf',
				renderer: function (v) {
					if (v == null) {
						return "";
					}
					if (v) {
						return "是";
					} else {
						return "否";
					}
				}
			}, {
				header: "是否EXT界面",
				dataIndex: 'IsExtPage',
				renderer: function (v) {
					if (v == null) {
						return "";
					}
					if (v) {
						return "是";
					} else {
						return "否";
					}
				}
			}, {
				header: "是否界面菜单",
				dataIndex: 'IsFunction',
				renderer: function (v) {
					if (v == null) {
						return "";
					}
					if (v) {
						return "是";
					} else {
						return "否";
					}
				}
			}, {
				xtype: 'datecolumn',
				format: 'Y年m月d日 H:i:s',
				header: "创建时间",
				width: 150,
				dataIndex: 'CreateTime'
			}],
			stripeRows: true
		}, cfg));
	},

	//onRender : function(){
	//    Infrastructure.Menu.GridPanel.superclass.onRender.call(this);
	//},

	onLoadUserMenu: function (p_userid) {
		userId = p_userid;
		var menuGrid = this;
		var menuStore = this.store;
		var menuSM = this.selModel;
		if (!this.initFlag) {
			var rootReocdData = {
				"Name": "所有菜单",
				"Code": "",
				"Id": "0",
				"ParentId": null,
				"Leaf": null,
				"Level": 0,
				"IsExtPage": null
			};
			menuStore.isLoadedNode = function (rc) {
				return true;
			};

			var rootReocd = new menuStore.recordType(rootReocdData, 0);
			menuStore.removeAll();
			menuStore.insert(0, rootReocd);
			//读取菜单
			menuStore.load({
				add: true
			});
			menuSM.lock();
			this.initFlag = true;
		}
		Ext.Ajax.request({
			url: '/InfraMenu/GetAllListByUserId',
			params: { 'Id': userId },
			success: function (response, opts) {
				var result = Ext.util.JSON.decode(response.responseText);
				if (result.success == false) {
					JsHelper.ShowError(result.msg);
				} else {
					var idsData = result.data;
					var len = idsData.length;
					for (var i = 0; i < len; i++) {
						var index = menuStore.find("Id", result.data[i].Id);
						if (index != -1) {
							menuSM.selections.add(menuStore.getAt(index));
							menuGrid.getView().onRowSelect(index);
						}
					}
				}
			}
		});
		this.saveBtn.setDisabled(false);
		menuSM.unlock();
	},

	onUnLoadUserMenu: function () {
		var menuSM = this.selModel;
		this.saveBtn.setDisabled(true);
		this.getSelectionModel().clearSelections();
		menuSM.lock();
	},

	onUpdateUserMenu: function () {
		var menuGrid = this;
		var menuStore = this.store;
		var menuSM = this.selModel;
		var ids = [];
		if (userId == '' || userId == null) {
			JsHelper.ShowError('用户不能为空!');
		} else {
			JsHelper.Confirm('是否更新用户菜单?', function (btn) {
				if (btn == 'yes') {
					var records = menuStore.getRange(1);
					for (var i = 0; i < records.length; i++) {
						if (menuSM.isSelected(menuStore.indexOf(records[i]))) {
							ids.push(records[i].get("Id"));
						}
					}
					//加载进度条
					Ext.MessageBox.show({
						msg: '正在提交数据到中心服务器...',
						progressText: '保存数据...',
						width: 300,
						wait: true,
						waitConfig: { interval: 1000 }
					});
					Ext.Ajax.request({
						url: '/InfraHospUser/SaveUserMenu',
						params: {
							'MId': ids.toString(),
							'Id': userId
						},
						success: function (response, opts) {
							Ext.MessageBox.hide();
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
							} else {
								Ext.Msg.alert('用户菜单', '更新成功');
							}
						},
						failure: function (form, action) {
							Ext.MessageBox.hide();
							JsHelper.ShowError(action.result.msg);
						}
					});
				}
			});
		}
	}
});
